<template>
  <div id="app">
    <van-cell center
              v-show="playShow"
              ref="player"
              :border="false"
              class="player"
              :style="playStyle"
              :label="musicAuthor">
      <template #title>
        <span>{{musicName.length>=16?musicName.slice(0,16)+'...':musicName}}</span>
      </template>
      <template #icon>
        <van-image :class="iconBool ? 'imgAvatar' : ''"
                   round
                   width="45"
                   height="45"
                   style="margin: 0.1rem 0.2rem"
                   :src="musicAvatarUrl"
                   @click="openMusicDtl" />
      </template>
      <template #right-icon>
        <van-icon :name="iconName"
                  size="25"
                  @click="handlePaly"
                  style="line-height: 1.5rem" />
        <van-icon style="padding: 0 5px 0 10px; line-height: 1.5rem"
                  name="wap-nav"
                  size="25"
                  @click="handleOpenOverlay" />
      </template>
    </van-cell>

    <audio controls="controls"
           style="display:none"
           ref="player"
           preload="true"
           :src="musicSrc"
           @canplay="getDuration"
           @timeupdate="onTimeupdate"
           @ended="handelEnded"></audio>

    <BottomPopup v-if="musicId"
                 ref="BottomPopup"
                 :currentTime="currentTime"
                 :playDuration="playDuration"
                 :lyricTime="lyricTime"
                 @handleInfoPlay="handleInfoPlay"
                 @handleNext="handleNext"
                 @handleLast="handleLast"
                 @handleOpenPlayList="handleOpenPlayList"
                 @handleClickPercentage="handleClickPercentage" />

    <van-popup v-model="popupShow"
               class="popupClass">
      <div class="van-ellipsis ellipsis"
           v-for="(music, index) in this.$store.state.songList"
           :key="index"
           :style="{ color: music.color }"
           @click="handleSwitchMusic(index)">
        <span>{{ music.name }} -</span>
        <template v-if="music.ar.length > 1">
          <span :style="{ color: music.color }"
                class="arName"
                v-for="(name, idx) in music.ar"
                :key="idx">
            {{ idx === music.ar.length - 1 ? name.name : name.name + "/" }}
          </span>
        </template>
        <template v-else>
          <span :style="{ color: music.color }"
                class="arName">
            {{ music.ar[0].name }}</span>
        </template>
      </div>
    </van-popup>

    <router-view />
  </div>
</template>

<script>
import BottomPopup from '../src/components/bottomPopup'
import { getSongUrl, checkMusic } from '../src/api/songSheet'
import { EventBus, formatTime } from '../currency'
export default {
  data() {
    return {
      iconName: 'play-circle-o',
      iconBool: false,
      playStyle: 'bottom: 50px;',
      musicList: [],
      musicSrc: '',
      musicAvatarUrl: '',
      musicName: '',
      musicAuthor: '',
      playDuration: '', // 播放时长
      musicId: '',
      playShow: false,
      currentTime: '0.00',
      popupShow: false,
      lyricTime: 0,
    }
  },
  components: { BottomPopup },
  watch: {
    // 监听路由改变样式
    '$route.path': function (val) {
      if (val == '/') {
        this.playStyle = 'bottom: 50px;'
      } else {
        this.playStyle = 'bottom: 0'
      }
    },
  },
  methods: {
    // 点击进度条
    handleClickPercentage(val) {
      this.$refs.player.currentTime = this.$refs.player.duration * val
      this.lyricTime = val * 100
    },
    handleOpenPlayList() {
      this.popupShow = true
    },
    // 上一首
    async handleLast() {
      if (this.$store.state.index < 0) {
        this.$store.commit('getIndex', this.$store.state.songList.length - 1)
      }
      this.$store.commit('getIndex', this.$store.state.index - 1)
      await this.getMusicData()
      this.handelOperationSon()
      this.startPlay()
    },
    // 下一首
    handleNext() {
      let state = this.$store.state
      if (state.index == state.songList.length - 1) {
        this.$store.commit('getIndex', 0)
      } else {
        this.$store.commit('getIndex', state.index + 1)
      }
      this.getMusicData()
      this.startPlay()
    },
    // 详情播放暂停
    handleInfoPlay(val) {
      if (this.iconBool) {
        this.pausePlay()
      } else {
        this.startPlay()
      }
    },
    // 播放结束
    async handelEnded() {
      this.$store.commit('getIndex', this.$store.state.index + 1)
      await this.getMusicData()
      this.$refs.BottomPopup.musicId = this.musicId
      this.$refs.BottomPopup.getMusicDtl()
      this.$refs.BottomPopup.getMusicLyric()
      this.startPlay()
    },
    // 打开歌曲详情
    openMusicDtl() {
      if (!this.musicId) return
      this.$refs.BottomPopup.musicId = this.musicId
      this.handelOperationSon()
    },
    // 操作子组件
    handelOperationSon() {
      this.$refs.BottomPopup.bottomPopup = true
      this.$refs.BottomPopup.getMusicDtl()
      this.$refs.BottomPopup.getMusicLyric()
    },
    // 获取音乐时长
    getDuration() {
      this.$refs.BottomPopup.MucLength = this.$refs.player.duration
      this.playDuration = formatTime(this.$refs.player.duration)
    },
    // 播放
    startPlay() {
      this.iconBool = true
      this.iconName = 'pause-circle-o'
      setTimeout(() => {
        this.$refs.player.play()
      }, 0)
    },
    // 暂停
    pausePlay() {
      this.iconBool = false
      this.iconName = 'play-circle-o'
      this.$refs.player.pause()
    },
    // 获取当前播放秒
    onTimeupdate(res) {
      let precent =
        this.$refs.player.currentTime / this.$refs.player.duration || 0
      this.currentTime = formatTime(res.target.currentTime)
      this.$refs.BottomPopup.percentage = precent.toFixed(2) * 100
      this.lyricTime = res.target.currentTime
    },
    async handleSwitchMusic(index) {
      this.$store.commit('getIndex', index)
      await this.getMusicData()
      this.$refs.BottomPopup.getMusicDtl()
      this.$refs.BottomPopup.getMusicLyric()
      this.startPlay()
    },
    handleOpenOverlay() {
      this.popupShow = true
    },
    // 播放点击
    handlePaly() {
      if (this.iconBool) {
        this.pausePlay()
        this.$refs.BottomPopup.playBool = true
      } else {
        this.startPlay()
        this.$refs.BottomPopup.playBool = false
      }
    },
    // 获取歌曲数据
    getMusicData() {
      let cookie = this.$store.state.userInfo.cookie
      let state = this.$store.state
      let current = state.songList[state.index] // 当前播放歌曲
      this.musicId = current.id
      setTimeout(() => {
        this.$refs.BottomPopup.playMusic = this.$refs.BottomPopup.pause
      }, 0)
      getSongUrl(current.id, cookie).then((res) => {
        if (res.data[0].url) {
          this.musicSrc = res.data[0].url
          this.playShow = true
          this.musicName = current.name
          this.musicAvatarUrl = current.al.picUrl
          this.musicAuthor = ''
          current.ar.forEach((ar, index) => {
            current.ar.length - 1 == index
              ? (this.musicAuthor += ar.name)
              : (this.musicAuthor += ar.name + ' / ')
          })
          this.startPlay()
        } else {
          return this.globalObj.$Dialog
            .alert({
              message: '暂无版权',
            })
            .then((res) => {
              this.handleNext()
            })
        }
      })
    },
  },
  mounted() {
    EventBus.$on('playMusic', (r) => {
      this.getMusicData()
    })
  },
}
</script>

<style>
*,
html,
body {
  font-family: auto;
  font-size: 15px;
  font-family: Arial, Helvetica, sans-serif;
}
p {
  margin: 0;
}

.player {
  position: fixed;
  width: 100%;
  height: 1.5rem;
  z-index: 10;
  padding: 0;
}

.playeContent {
  width: 80%;
  height: 50%;
  z-index: 100;
  margin: 40% auto;
  overflow: auto;
  background: #fff;
  padding: 10px;
  border-radius: 12px;
}

@keyframes iconRotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.imgAvatar {
  animation: iconRotate 10s linear infinite;
}

.popupClass {
  width: 80%;
  height: 40%;
  font-size: 0.4rem;
  overflow: auto;
  padding: 5%;
  border-radius: 10px;
}
.arName {
  font-size: 0.35rem;
  color: rgb(107, 107, 107);
}
.ellipsis {
  padding: 0.35rem 0;
}
[class*='van-hairline']::after {
  border: none;
}
.player .van-cell__title {
  padding-top: 0.05rem;
}
</style>
